package com.suse.ecommerce.interceptor;

import com.suse.ecommerce.serviceImp.RedisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class RefershInterface implements HandlerInterceptor {
    @Autowired
    private RedisService redisService;

   /* @PostConstruct
    public void setRedisService(){
        ApplicationContext context=new ClassPathXmlApplicationContext("classpath:/spring/applicationContext.xml");
        redisService = context.getBean(RedisService.class);
    }*/

    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
        String requestURI = httpServletRequest.getRemoteHost();
        String s = redisService.get(requestURI);
        if(s==null){
            redisService.set(requestURI,1+"",5);
        }else if(Integer.parseInt(s)<5){
            redisService.increment(requestURI);
        }else if(Integer.parseInt(s)>=5){
            //说明该用户刷新太频繁，禁止用户登录20秒
            redisService.expire(requestURI,10);
            System.out.println("request intercepter");
            httpServletResponse.sendError(404);
            return false;
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}
